<template>
  <view class="profile-container">
    <!-- 标题区域 -->
    <view class="title-bar">
      <text class="title-text">我的资料</text>
    </view>
    
    <!-- 资料表单 -->
    <view class="profile-form">
      <!-- 头像 -->
      <view class="form-item avatar-item">
        <view class="item-label">
          <text class="label-text">头像</text>
        </view>
        <view class="avatar-container" @tap="handleChangeAvatar">
          <image class="avatar-image" :src="getAvatarUrl()" mode="aspectFill"></image>
      
        </view>
      </view>
      
      <!-- 姓名 -->
      <view class="form-item">
        <view class="item-label">
          <text class="label-text">姓名</text>
        </view>
        <view class="input-container">
          <input 
            class="input-field" 
            type="text" 
            v-model="userInfo.name"
            maxlength="20"
          />
        </view>
      </view>
      
      <!-- 身份证号 -->
      <view class="form-item">
        <view class="item-label">
          <text class="label-text">身份证号</text>
        </view>
        <view class="input-container">
          <input 
            class="input-field" 
            type="idcard" 
            v-model="userInfo.idCard"
            maxlength="18"
          />
        </view>
      </view>
      
      <!-- 联系电话 -->
      <view class="form-item">
        <view class="item-label">
          <text class="label-text">联系电话</text>
        </view>
        <view class="input-container">
          <input 
            class="input-field" 
            type="number" 
            v-model="userInfo.phone"
            maxlength="11"
          />
        </view>
      </view>
    </view>

      <!-- 团队信息 -->
      <view class="profile-form">
        <!-- 所在城市 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">所在城市</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="text" 
              v-model="userInfo.city"
              maxlength="20"
            />
          </view>
        </view>
        
        <!-- 团队性质 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">团队性质</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="text" 
              v-model="userInfo.teamType"
              maxlength="20"
            />
          </view>
        </view>
        
        <!-- 团队名称 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">团队名称</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="text" 
              v-model="userInfo.teamName"
              maxlength="30"
            />
          </view>
        </view>
        
        <!-- 职位 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">职位</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="text" 
              v-model="userInfo.position"
              maxlength="20"
            />
          </view>
        </view>
        
        <!-- 礼仪人数 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">礼仪人数</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="number" 
              v-model="userInfo.memberCount"
              maxlength="3"
            />
          </view>
        </view>
        
        <!-- 擅长类型 -->
        <view class="form-item">
          <view class="item-label">
            <text class="label-text">擅长类型</text>
          </view>
          <view class="input-container">
            <input 
              class="input-field" 
              type="text" 
              v-model="userInfo.specialty"
              maxlength="50"
            />
          </view>
        </view>
      </view>
    
    <!-- 保存按钮 -->
    <view class="save-button-container">
      <view class="save-button" @tap="handleSave">
        <text class="save-text">保存</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShow, onUnload, onBackPress } from '@dcloudio/uni-app'
import { apiService, ApiService } from '/pages/utils/api.js'
import { useUserStore } from '/pages/store/user.js'

const userStore = useUserStore()

// 用户信息
const userInfo = ref({
  avatar: '',      // 头像
  name: '',        // 姓名
  idCard: '',      // 身份证号
  phone: '',       // 联系电话
  city: '',        // 所在城市
  teamType: '',    // 团队性质
  teamName: '',    // 团队名称
  position: '',    // 职位
  memberCount: '', // 礼仪人数
  specialty: '',    // 擅长类型,
  rowid: ''
})

// 添加临时头像路径变量
const tempAvatarPath = ref('')

// 单文件上传封装：返回 fileUrl
const uploadFileAndGetUrl = (filePath, directory = 'avatar') => {
  return new Promise((resolve, reject) => {
    const task = uni.uploadFile({
      url: 'https://api.shmodio.cn/alioss',
      filePath,
      name: 'file',
      formData: { directory },
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          const url = data?.data?.fileUrl || data?.url;
          if (url) return resolve(url);
          reject(new Error(data?.message || '上传失败'));
        } catch {
          reject(new Error('响应解析失败'));
        }
      },
      fail: reject
    });
  });
};

// 更换头像 - 修改为只选择图片，不立即上传
const handleChangeAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      console.log('选择图片成功:', res.tempFilePaths)
      const tempFilePath = res.tempFilePaths[0]
      
      // 只保存临时路径，不立即上传
      tempAvatarPath.value = tempFilePath
      // 显示预览图片
      userInfo.value.avatar = tempFilePath
      
      uni.showToast({
        title: '头像已选择',
        icon: 'success'
      })
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 保存资料 - 修改为在保存时上传头像
const handleSave = async () => {
  uni.showLoading({
    title: '保存中...'
  })
  
  try {
    // 如果有临时头像路径，先上传头像
    if (tempAvatarPath.value) {
      uni.showLoading({
        title: '上传头像中...'
      })
      
      try {
        const uploadedUrl = await uploadFileAndGetUrl(tempAvatarPath.value, 'avatar')
        userInfo.value.avatar = uploadedUrl
        tempAvatarPath.value = '' // 清空临时路径
      } catch (error) {
        console.error('头像上传失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '头像上传失败',
          icon: 'none'
        })
        return
      }
    }
    
    // 调用API更新用户信息
    await apiService.updateUserInfo(userInfo.value)
    
    uni.hideLoading()
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    })
    
    // 保存成功后统一返回到profile index页面
    setTimeout(() => {
      // 发送刷新事件
      uni.$emit('refreshUserInfo')
      
      // 标记不需要处理自定义返回，因为我们主动返回了
      shouldHandleCustomBack = false
      
      // 统一返回到profile index页面
      uni.switchTab({
        url: '/pages/tabs/profile/index'
      })
    }, 1500)
  } catch (error) {
    console.error('保存失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  }
}

// 获取头像URL的方法
const getAvatarUrl = () => {
  // 优先使用已经解析好的 avatar 字段
  if (userInfo.value.avatar && userInfo.value.avatar.trim() !== '') {
    return userInfo.value.avatar
  }
  
  // 如果 avatar 字段为空，尝试从原始数据解析
  const avatarData = userInfo.value['68b8f69a8326c4bbc62df3d8']
  if (avatarData && avatarData.trim() !== '') {
    try {
      const parsedAvatar = JSON.parse(avatarData)
      // 检查是否是数组且包含文件信息
      if (Array.isArray(parsedAvatar) && parsedAvatar.length > 0) {
        const fileInfo = parsedAvatar[0]
        // 优先使用 original_file_full_path，如果没有则使用 file_path + file_name
        return fileInfo.original_file_full_path || 
               (fileInfo.file_path + fileInfo.file_name) || 
               '/static/logo.png'
      }
      return '/static/logo.png'
    } catch (error) {
      console.error('解析头像失败:', error)
      return '/static/logo.png'
    }
  }
  return '/static/logo.png'
}


// 添加一个变量来跟踪是否是从二维码页面跳转过来的
let isFromQrcode = false

// 添加一个变量来标记是否需要处理自定义返回
let shouldHandleCustomBack = false

onLoad((options) => {
  console.log('我的资料页面加载完成')
  
  // 设置自定义导航栏返回处理
  // #ifdef MP-WEIXIN
  // 微信小程序：监听页面卸载事件
  shouldHandleCustomBack = true
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  if (currentPage) {
    // 保存原始的事件处理
    const originalOnUnload = currentPage.onUnload
    // 重写onUnload方法
    currentPage.onUnload = function() {
      console.log('页面卸载，准备处理返回逻辑')
      if (shouldHandleCustomBack) {
        // 延迟执行返回，确保页面卸载完成
        uni.$emit('refreshUserInfo')
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/tabs/profile/index'
          })
        }, 150)
      }
      // 如果存在原始的方法，也执行它
      if (originalOnUnload && typeof originalOnUnload === 'function') {
        originalOnUnload.call(this)
      }
    }
  }
  // #endif
  
  // 判断跳转来源并打印日志
  if (options && options.from === 'qrcode') {
    console.log('我是从pages/qrcode/qrcode.vue页面跳转的')
    isFromQrcode = true
  }
  
  // 这里可以添加初始化用户信息的逻辑
  const res = userStore.userInfo
  console.log('myProfile的用户信息', res);
  
  // 安全解析头像，如果为空字符串则使用默认值
  const avatarData = res['68b8f69a8326c4bbc62df3d8']
  if (avatarData && avatarData.trim() !== '') {
    try {
      const parsedAvatar = JSON.parse(avatarData)
      // 检查是否是数组且包含文件信息
      if (Array.isArray(parsedAvatar) && parsedAvatar.length > 0) {
        const fileInfo = parsedAvatar[0]
        console.log('fileInfo', fileInfo);
        userInfo.value.avatar = fileInfo.original_file_full_path || 
               (fileInfo.file_path + fileInfo.file_name) || ''
      } else {
        userInfo.value.avatar = ''
      }
    } catch (error) {
      console.error('解析头像数据失败:', error)
      userInfo.value.avatar = ''
    }
  } else {
    userInfo.value.avatar = ''
  }
  
  userInfo.value.name = res['68a6b776096ba6d65c500839'] || ''
  userInfo.value.idCard = res['68b8f91e8326c4bbc62df63b'] || ''
  userInfo.value.phone = res['6886e725427a9931f8180b17'] || ''
  userInfo.value.city = res['68b8f95c8326c4bbc62df659'] || ''
  userInfo.value.teamType = res['68b8f9918326c4bbc62df681'] || ''
  userInfo.value.teamName = res['68b8f9918326c4bbc62df682'] || ''
  userInfo.value.position = res['68b8f9918326c4bbc62df683'] || ''
  userInfo.value.memberCount = res['68b8f9918326c4bbc62df684'] || ''
  userInfo.value.specialty = res['68b8f9918326c4bbc62df685'] || ''
  userInfo.value.rowid = res['rowid'] || ''
})

// onShow(() => {
//   console.log('我的资料页面显示')
//   // 监听刷新用户信息事件
//   uni.$on('refreshUserInfo', () => {
//     console.log('收到刷新用户信息事件')
//     // 重新获取用户信息并更新
//     const res = uni.getStorageSync('userInfo')
//     const avatarData = res['68b8f69a8326c4bbc62df3d8']
//     if (avatarData && avatarData.trim() !== '') {
//       try {
//         const parsedAvatar = JSON.parse(avatarData)
//         // 检查是否是数组且包含文件信息
//         if (Array.isArray(parsedAvatar) && parsedAvatar.length > 0) {
//           const fileInfo = parsedAvatar[0]
//           userInfo.value.avatar = fileInfo.original_file_full_path || 
//                                  (fileInfo.file_path + fileInfo.file_name) || ''
//         } else {
//           userInfo.value.avatar = ''
//         }
//       } catch (error) {
//         console.error('解析头像数据失败:', error)
//         userInfo.value.avatar = ''
//       }
//     } else {
//       userInfo.value.avatar = ''
//     }
    
//     userInfo.value.name = res['68a6b776096ba6d65c500839'] || ''
//     userInfo.value.idCard = res['68b8f91e8326c4bbc62df63b'] || ''
//     userInfo.value.phone = res['6886e725427a9931f8180b17'] || ''
//     userInfo.value.city = res['68b8f95c8326c4bbc62df659'] || ''
//     userInfo.value.teamType = res['68b8f9918326c4bbc62df681'] || ''
//     userInfo.value.teamName = res['68b8f9918326c4bbc62df682'] || ''
//     userInfo.value.position = res['68b8f9918326c4bbc62df683'] || ''
//     userInfo.value.memberCount = res['68afed7e6b50e0d4f7a76b39'] || ''
//     userInfo.value.specialty = res['68b8f9918326c4bbc62df685'] || ''
//     userInfo.value.rowid = res['rowid'] || ''
//   })
// })

// 监听物理返回键
onBackPress(() => {
  console.log('物理返回键被按下，统一返回到profile index页面')
  // 标记不需要处理自定义返回，因为我们主动返回了
  shouldHandleCustomBack = false
   uni.$emit('refreshUserInfo')
  // 统一返回到 profile index 页面
  uni.switchTab({
    url: '/pages/tabs/profile/index'
  })
  return true // 阻止默认返回行为
})

// 页面卸载时的处理
onUnload(() => {
  // 页面卸载时移除事件监听，避免内存泄漏
  // uni.$off('refreshUserInfo')
})
</script>

<style lang="scss" scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0 30rpx;
}

/* 添加页面级样式，确保整个页面背景色一致 */
page {
  background-color: #f5f5f5;
}

.title-bar {
  padding: 20rpx 0;
  position: relative;
  margin: 20rpx 0;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 8rpx;
    height: 28rpx;
    background-color: #FF6B9B;
    border-radius: 4rpx;
  }
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  padding-left: 24rpx;
}

.profile-form {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 30rpx;
  margin-top: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.avatar-item {
    align-items: flex-start;
    padding: 30rpx 0;
  }
}

.item-label {
  flex-shrink: 0;
  width: 160rpx;
}

.label-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.input-container {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  justify-content: flex-end;
}

.input-field {
  width: 200rpx;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
  border: none;
  outline: none;
  text-align: right;
  
  &::placeholder {
    color: #999;
  }
}

.avatar-container {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  cursor: pointer;
}

.avatar-image {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  border: 4rpx solid #f0f0f0;
}

.save-button-container {
  position: fixed;
  bottom: 40rpx;
  left: 30rpx;
  right: 30rpx;
  z-index: 100;
}

.save-button {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #FF6B9B 0%, #FF9E9E 100%);
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 20rpx rgba(255, 107, 155, 0.3);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 10rpx rgba(255, 107, 155, 0.3);
  }
}

.save-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 600;
}
</style>
